<template>
  <div class="avatar-container" v-if="showAvatar">
    <div class="avatar-box">
      <div class="avatar-header">
        <span class="title">头像管理</span>
        <el-button class="close-btn" type="text" @click="handleClose">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <el-scrollbar class="avatar-scrollbar">
        <div class="avatar-grid">
          <div v-for="(avatar, index) in avatarList" :key="avatar.id" class="avatar-item">
            <div class="avatar-wrapper" @mouseenter="showDelete(index)" @mouseleave="hideDelete(index)">
              <el-image 
                :src="avatar.image" 
                fit="cover" 
                class="avatar-image"
                :preview-src-list="[avatar.image]"
              />
              <div v-if="showDeleteBtn[index]" class="delete-btn" @click="handleDelete(avatar)">
                <el-button type="danger" size="small" circle>
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          <div class="avatar-item">
            <div class="avatar-wrapper upload-wrapper">
              <el-upload
                :show-file-list="false"
                :action="uploadImgUrl"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :headers="headers"
                class="avatar-uploader"
                v-model="imageUrl"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar-image" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Delete, Close, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listAvatar, addAvatar, delAvatar } from '@/api/manage/avatar'
import { getToken } from '@/utils/auth'

const showAvatar = ref(false)
const avatarList = ref([])
const showDeleteBtn = ref([])
const loading = ref(false)
const imageUrl = ref('')
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/manage/avatar"); // 上传的图片服务器地址
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
});

const headers = ref({
  Authorization: 'Bearer ' + getToken()
})

// 获取头像列表
const getAvatarList = () => {
  showAvatar.value = true
  loading.value = true
  listAvatar().then(res => {
    if (res) {
      avatarList.value = res.rows || []
      showDeleteBtn.value = new Array(avatarList.value.length).fill(false)
    } else {
      avatarList.value = []
      showDeleteBtn.value = []
      ElMessage.warning('获取头像列表失败')
    }
  }).catch(error => {
    console.error('获取头像列表出错:', error)
    ElMessage.error('获取头像列表失败')
    avatarList.value = []
    showDeleteBtn.value = []
  }).finally(() => {
    loading.value = false
  })
}

// 关闭头像管理
const handleClose = () => {
  showAvatar.value = false
}

// 显示删除按钮
const showDelete = (index) => {
  showDeleteBtn.value[index] = true
}

// 隐藏删除按钮
const hideDelete = (index) => {
  showDeleteBtn.value[index] = false
}

// 处理删除
const handleDelete = (avatar) => {
  ElMessageBox.confirm(
    '确定要删除该头像吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delAvatar(avatar.id).then(() => {
      ElMessage.success('删除成功')
      getAvatarList()
    })
  }).catch(() => {})
}

// 上传前检查
function handleBeforeUpload(file) {
  // 检查文件类型
  const fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase();
  const isTypeValid = props.fileType.some(type => {
    return fileExtension === type.toLowerCase() || file.type.includes(type.toLowerCase());
  });

  if (!isTypeValid) {
    ElMessage.error(`文件格式不正确，请上传 ${props.fileType.join("、")} 格式的图片`);
    return false;
  }

  // 检查文件大小
  const isSizeValid = file.size / 1024 / 1024 < props.fileSize;
  if (!isSizeValid) {
    ElMessage.error(`图片大小不能超过 ${props.fileSize}MB`);
    return false;
  }

  // 检查图片尺寸
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      const img = new Image();
      img.src = e.target.result;
      img.onload = () => {
        const width = img.width;
        const height = img.height;
        // 建议头像尺寸为正方形，这里设置宽高比在0.8-1.2之间
        const ratio = width / height;
        if (ratio < 0.8 || ratio > 1.2) {
          ElMessage.warning('建议上传正方形图片，当前图片比例可能影响显示效果');
        }
        resolve(true);
      };
      img.onerror = () => {
        ElMessage.error('图片加载失败，请重新选择');
        reject(false);
      };
    };
    reader.onerror = () => {
      ElMessage.error('文件读取失败，请重新选择');
      reject(false);
    };
  });
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    ElMessage.success('上传成功');
    getAvatarList();
    imageUrl.value = ''; // 清空预览图
  } else {
    ElMessage.error(res.msg || '上传失败');
  }
}

// 上传失败回调
function handleUploadError(error) {
  console.error('上传失败:', error);
  ElMessage.error('上传失败，请重试');
}

// 暴露方法给父组件
defineExpose({
  getAvatarList
})
</script>

<style scoped>
.avatar-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2000;
  width: 50%;
  max-width: 700px;
}

.avatar-box {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  display: flex;
  flex-direction: column;
  max-height: 70vh;
}

.avatar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.avatar-scrollbar {
  height: calc(70vh - 60px);
  overflow-x: hidden;
}

.avatar-header .title {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

.close-btn {
  padding: 0;
  font-size: 14px;
}

.avatar-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 改为每行5个 */
  gap: 12px;
  padding: 5px;
}

.avatar-item {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
}

.avatar-wrapper {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.upload-wrapper {
  background-color: #f5f7fa;
  border-radius: 50%;
  transition: all 0.3s;
}

.upload-wrapper:hover {
  background-color: #e4e7ed;
}

.avatar-uploader {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  transition: transform 0.3s;
}

.avatar-image:hover {
  transform: scale(1.05);
}

.delete-btn {
  position: absolute;
  bottom: -5px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 100%;
  padding: 0;
  border: none;
  background: none;
}

:deep(.el-upload-dragger:hover) {
  border: none;
  background: none;
}

/* 自定义滚动条样式 */
:deep(.el-scrollbar__bar.is-horizontal) {
  display: none;
}

@media screen and (max-width: 768px) {
  .avatar-container {
    width: 90%;
  }
  
  .avatar-grid {
    grid-template-columns: repeat(3, 1fr); /* 在小屏幕上每行3个 */
  }
}
</style> 